<template>
    <div>
        <Drawer :closable="false" placement="right" v-model="courseDrawer" width="60%" :title="drawerTitle">
            <Row>
                <Col>
                    <Card :shadow="shadow">
                        <Row>
                            <Form ref="form" :model="form" :label-width="80" :rules="formValidate" style="position:relative">
                                <FormItem label="课程名称" prop="courseTitle">
                                    <Input v-model="form.courseTitle" style="width:600px"/>
                                </FormItem>
                                <FormItem label="分类名称" prop="typeName">
                                    <Input v-model="form.typeName" style="width:600px"/>
                                </FormItem>
                                <FormItem label="课程排序" prop="sortOrder">
                                    <Input v-model="form.sortOrder" type="number" style="width:600px"/>
                                </FormItem>
                                <FormItem label="课程介绍" prop="courseContent">
                                    <div ref="editor"></div>
                                </FormItem>
                                <Form-item label class="br">
                                    <Button @click="editHTML" icon="ios-create-outline">编辑HTML代码</Button>
                                    <Button @click="fullscreenModal=true" icon="md-eye">预览</Button>
                                </Form-item>
                                <FormItem label="封面图" prop="courseImage">
                                    <upload-input :fileUrl="form.courseImage" :fileSize="fileSize" fileWh="750*566" @on-change="handleUpload" width="400px" ref="upload"></upload-input>
                                </FormItem>
                                <FormItem label="选择讲师" prop="lecturerId">
                                    <user-choose buttonText="选择讲师"  :userType="userType" @on-change="handleSelectUser" ref="user"></user-choose>
                                </FormItem>
                                <Form-item class="br">
                                    <Button type="primary" :loading="submitLoading" @click="handelSubmit" style="width:100px">提交</Button>
                                    <Button @click="handelCancel">取消</Button>
                                </Form-item>
                                <Spin size="large" fix v-if="loading"></Spin>
                            </Form>
                        </Row>
                    </Card>
                </Col>
            </Row>
            <!-- html编辑 -->
            <Modal title="编辑html代码" v-model="showHTMLModal" :mask-closable="false" :width="900" :fullscreen="full">
                <Input v-if="!full" v-model="dataEdit" :autosize="true" type="textarea" style="max-height:60vh;overflow:auto"/>
                <Input v-if="full" v-model="dataEdit" :autosize="true" type="textarea"/>
                <div slot="footer">
                    <Button @click="full=!full" icon="md-expand">全屏开/关</Button>
                    <Button @click="editHTMLOk" type="primary" icon="md-checkmark-circle-outline">确定保存</Button>
                </div>
            </Modal>
            <Modal title="预览" v-model="fullscreenModal" fullscreen>
                <div v-html="form.courseContent">{{form.courseContent}}</div>
                <div slot="footer">
                    <Button @click="fullscreenModal=false">关闭</Button>
                </div>
            </Modal>
        </Drawer>
    </div>
</template>
<script>
    import {uploadFile} from "@/api/index";
    import {addContinueCourse, editCourse, getCourse, getUserChosed} from "@/api/bus";
    import userChoose from "../../my-components/flyme/user-choose";
    import uploadInput from "@/views/my-components/flyme/upload-input";
    import E from "wangeditor";
    // 表情包配置 自定义表情可在该js文件中统一修改
    import {sina} from "@/libs/emoji";


    let editor = null;
    var xss = require("xss");
    export default {
        name: "add_course2",
        components: {
            userChoose,
            uploadInput
        },
        data() {
            return {
                type: 0,
                userType: "UT_LECTURER",
                loading: false, // 表单加载状态
                selectUsers: [],
                shadow: false,
                fileSize: 400,
                indexTagList: [],//课程模块
                courseTypeList: [],//分类列表
                drawerTitle: "添加课程",
                courseDrawer: false,
                userModalVisible: false,
                modalTitle: "", // 添加或编辑标题
                form: {
                    // 添加或编辑表单对象初始化数据
                    typeName: "",//分类名称
                    courseTitle: "",
                    courseContent: "",
                    courseTypeId: "",
                    indextagId: "0",
                    sortOrder: 1,
                    isFree: 1,
                    isSlider: 0,
                    lecturerId: "",
                    onLine: 1,
                    isVipFree: 1,
                    courseImage: "",
                    coursePrice: 0,
                    range: 0,
                    scoreCourse: 0
                },
                formValidate: {
                    // 表单验证规则
                    typeName: [{required: true, message: "分类名称不能为空", trigger: "blur"}],
                    courseTitle: [{required: true, message: "课程名称不能为空", trigger: "blur"}],
                    courseContent: [{required: true, message: "课程介绍不能为空", trigger: "blur"}],
                    courseImage: [{required: true, message: "封面图不能为空", trigger: "blur"}]
                },
                submitLoading: false, // 添加或编辑提交状态
                dictMessageType: [],
                dictSex: [],
                dataEdit: "", // 编辑数据
                showHTMLModal: false, // 显示html
                full: false, // html全屏开关
                fullscreenModal: false, // 显示全屏预览
                backRoute: ""
            };
        },
        methods: {
            init() {
                this.initEditor();
            },
            showCourseDrawer(params) {
                if (params.courseId) {
                    this.type = 1;
                    this.drawerTitle = "编辑课程";
                    this.form.id = params.courseId;
                    this.getData();
                } else {
                    this.$refs.form.resetFields();
                    editor.txt.html("");
                    this.drawerTitle = "添加课程";
                    this.form.courseTypeId = params.courseTypeId;
                    this.type = 0;
                    this.courseDrawer = true;
                }
            },
            clearUser() {
                this.$refs.user.clearSelectUser();
            },
            initEditor() {
                let that = this;
                editor = new E(this.$refs.editor);
                editor.customConfig.onchange = html => {
                    this.form.courseContent = html;
                };
                editor.customConfig.uploadImgServer = uploadFile;
                editor.customConfig.uploadImgHeaders = {
                    Authorization: that.getStore("accessToken")
                };
                editor.customConfig.uploadFileName = "file";
                editor.customConfig.uploadImgHooks = {
                    before: function (xhr, editor, files) {
                    },
                    success: function (xhr, editor, result) {
                    },
                    fail: function (xhr, editor, result) {
                        that.$Message.error("上传图片失败");
                    },
                    error: function (xhr, editor) {
                        that.$Message.error("上传图片出错");
                    },
                    timeout: function (xhr, editor) {
                        that.$Message.error("上传图片超时");
                    },
                    customInsert: function (insertImg, result, editor) {
                        if (result.status === true) {
                            let url = result.data.fileUrl;
                            insertImg(url);
                            that.$Message.success("上传图片成功");
                        } else {
                            that.$Message.error(result.info);
                        }
                    }
                };
                editor.customConfig.fontNames = ["微软雅黑", "宋体", "黑体", "Arial"];
                editor.customConfig.emotions = [
                    {
                        title: "新浪",
                        type: "image",
                        content: sina
                    }
                ];
                editor.create();
            },
            editHTML() {
                this.dataEdit = this.form.courseContent;
                this.showHTMLModal = true;
            },
            editHTMLOk() {
                editor.txt.html(this.dataEdit);
                this.form.courseContent = xss(this.dataEdit);
                this.showHTMLModal = false;
            },
            getData() {
                this.loading = true;
                getCourse(this.form.id).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        editor.txt.html(res.data.courseContent);
                        this.form = res.data;
                        const that = this
                        setTimeout(function () {
                            that.$refs.user.getUserChosed(res.data.users);
                        },100);
                        this.courseDrawer = true;
                    }
                });
            },
            handelSubmit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        if(this.form.courseImage === ''){
                            this.$Message.error("请上传封面图");
                            return false;
                        }
                        this.submitLoading = true;
                        this.form.isContinue = 1
                        if (this.type === 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.form.id;
                            // 用户id数据
                            let ids = [];
                            this.selectUsers.forEach(e => {
                                ids.push(e.id);
                            });
                            this.form.lecturerId = ids;
                            this.form.scoreCourse = 0;
                            this.form.isSlider = 0;
                            this.form.isVipFree = 0;
                            this.form.isFree = 0;
                            this.form.courseTypeId = '';
                            this.form.indextagId = '';
                            this.form.recommend = 0;
                            addContinueCourse(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.$parent.getDataList();
                                    this.courseDrawer = false;
                                }
                            });
                        } else if (this.type === 1) {
                            // 编辑
                            editCourse(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.$parent.getDataList();
                                    this.courseDrawer = false;
                                }
                            });
                        }
                    }
                });
            },
            handleSelectUser(v) {
                this.form.lecturerId = v[0].id;
                this.selectUsers = v;
            },
            handelCancel() {
                this.courseDrawer = false;
            },
            handleUpload(v) {
                if (v.fileUrl) {
                    this.form.courseImage = v.fileUrl;
                }else{
                    this.form.courseImage = v;
                }
            },
        },
        mounted() {
            this.init();
        },
        watch: {
            // 监听路由变化
            $route(to, from) {
                if (to.name == "add_course") {
                    this.type = this.$route.query.type;
                    if (this.type == 1) {
                        this.form.id = this.$route.query.courseId;
                        this.getData();
                    }
                }
            }
        }
    };
</script>